<?php

namespace App\Http\Controllers\Admin\System;

use App\Enums\ResponseEnum;
use App\Http\Controllers\AdminController;
use App\Models\System\Menus;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Spatie\Permission\Models\Permission;

class MenusController extends AdminController
{

    public function data(Request $request)
    {
        $model = Menus::query()->select(['id', 'name', 'display_name', 'path', 'icon', 'parent_id as parentId', 'genre', 'status', 'created_at']);
        $genres = $request->get('genre');
        if (is_array($genres)) {
            $model->whereIn('genre', $genres);
        }
        $list = $model->get()->toArray();
        return $this->succeed($list);
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => ['required','max:150','unique:system_menus'],
            'display_name' => ['required']
        ]);
        $data = $request->only(['parentId', 'name', 'display_name', 'genre', 'icon', 'path', 'status']);
        DB::transaction(function () use ($data) {
            Permission::query()->create(['name' => $data["name"], 'guard_name' => static::GUARD_NAME]);
            $model = Menus::query()->create([
                'parent_id' => (int)$data["parentId"],
                'name' => $data["name"],
                'display_name' => $data["display_name"],
                'genre' => (int)$data['genre'],
                'icon' => (string)$data["icon"],
                'path' => (string)$data["path"],
                'status' => (int)$data["status"]
            ]);
            $this->createSyslog('添加了一条后台菜单记录', $data, $model);
        });
        return $this->succeed();
    }

    public function update(Request $request, $id)
    {
        $request->validate([
            'name' => ['required','max:150','unique:system_menus,name,'.$id.',id'],
            'display_name' => ['required']
        ]);
        $model = Menus::query()->findOrFail($id);
        $data = $request->only(['parentId', 'name', 'display_name', 'genre', 'icon', 'path', 'status']);
        DB::transaction(function () use ($model, $data) {
            if ($model['name'] !== $data['name']) {
                Permission::query()->updateOrCreate(['name' => $model['name']], ['name' => $data['name']]);
            }
            $model->update([
                'parent_id' => (int)$data["parentId"],
                'name' => $data["name"],
                'display_name' => $data["display_name"],
                'genre' => (int)$data['genre'],
                'icon' => (string)$data["icon"],
                'path' => (string)$data["path"],
                'status' => (int)$data["status"]
            ]);
            $this->createSyslog('更新了一条后台菜单记录', $data, $model);
        });
        return $this->succeed();
    }

    public function destroy(Request $request)
    {
        $request->validate(['ids' => ['required','array','max:'.static::QUERY_LIMIT]]);
        $ids = $request->get('ids');
        $list = Menus::query()->select(['id', 'name'])->whereIn('id', $ids)->limit(static::QUERY_LIMIT)->withCount('children')->get();
        abort_if($list->isEmpty(), ResponseEnum::DELETE_NOT_EXIST_ERROR);
        DB::transaction(function () use ($list) {
            foreach ($list as $row) {
                abort_if($row->children_count > 0, ResponseEnum::PERMISSION_EXISTS_DELETE_ERROR);
                Permission::query()->where('name', $row->name)->where('guard_name', static::GUARD_NAME)->delete();
                $row->delete();
                $this->createSyslog('删除了一条后台菜单记录', [], $row);
            }
        });
        return $this->succeed();
    }
}
